package com.candy.common.config;

import com.alibaba.fastjson2.JSON;
import com.candy.common.constant.CommonConstant;
import com.candy.common.filter.XssFilter;
import com.candy.common.properties.SystemProperties;
import jakarta.servlet.Filter;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;

/**
 * filter配置
 *
 * @author rong xi
 * @date 2023/09/14 10:27
 * @version 1.0
 */
@Configuration
@AllArgsConstructor
public class FilterConfig {

	private final SystemProperties systemProperties;


	@Bean
	@ConditionalOnProperty(prefix = "candy.system", name = "xss-enabled", havingValue = "true")
	public FilterRegistrationBean<Filter> xssFilterRegistrationBean() {
		// 创建一个 FilterRegistrationBean 对象，并传入一个 IdempotentFilter 对象作为参数
		FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<>(new XssFilter());
		// 设置该 FilterRegistrationBean最开始执行
		filterRegistrationBean.setOrder(0);
		// 设置该 FilterRegistrationBean 对象为启用状态
		filterRegistrationBean.setEnabled(true);
		// 向该 FilterRegistrationBean 对象添加 URL 模式 /*，表示该过滤器应用到所有 URL
		filterRegistrationBean.addUrlPatterns("/*");
		// 设置过滤器名称
		filterRegistrationBean.setName("xssFilter");
		// 设置XSS不过滤url
		Map<String, String> initParameters = new HashMap<>();
		initParameters.put(CommonConstant.XSS_EXCLUDES_PARAM, systemProperties.getXssExcludes());
		filterRegistrationBean.setInitParameters(initParameters);
		// 返回该 FilterRegistrationBean 对象
		return filterRegistrationBean;
	}

}